package boun.center;



import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;

public class SocketUtil {
	private static String serverIP = "192.168.151.78";
	private static InputStream listenConnFromSocket(int port) throws IOException{
		ServerSocket ss = new ServerSocket(port);
		Socket s = ss.accept();
		InputStream is = s.getInputStream();
		s.close();
		ss.close();
		return is;
	}
	public static ArrayList<CmpeNews> fetchCmpeNews() throws IOException, ClassNotFoundException, ParseException{
		return (ArrayList<CmpeNews>) sendFetchRequestToServer(new DataPacket(CmpeNews.class.getName(),null));
	}
	public static ArrayList<BounNews> fetchBounNews() throws IOException, ClassNotFoundException{
		return (ArrayList<BounNews>) sendFetchRequestToServer(new DataPacket(BounNews.class.getName(),null));
	}
	public static ArrayList<Tweet> fetchTwitter() throws IOException, ClassNotFoundException{
		return (ArrayList<Tweet>) sendFetchRequestToServer(new DataPacket(Tweet.class.getName(),null));
	}
	public static ArrayList<CalendarEvent> fetchCalendar() throws IOException, ClassNotFoundException {
		return (ArrayList<CalendarEvent>) sendFetchRequestToServer(new DataPacket(CalendarEvent.class.getName(),null));
	}
	public static ArrayList<String> fetchSchedule(HashMap<String,Object> map) throws IOException, ClassNotFoundException{
		return (ArrayList<String>) sendFetchRequestToServer(new DataPacket(BusSchedule.class.getName(),map));
	}
	private static ArrayList<?> sendFetchRequestToServer(DataPacket packet) throws IOException, ClassNotFoundException {
		Socket socket = new Socket(serverIP,2332);
		OutputStream os = socket.getOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(packet);
		InputStream is = socket.getInputStream();
		ObjectInputStream ois = new ObjectInputStream(is);
		ArrayList<?> result = null;
		if(packet.getHeader().equals(CmpeNews.class.getName())){
			result = (ArrayList<CmpeNews>)ois.readObject();
		}else if(packet.getHeader().equals(BounNews.class.getName())) {
			result = (ArrayList<BounNews>)ois.readObject();
		}else if(packet.getHeader().equals(Tweet.class.getName())){
			result = (ArrayList<Tweet>) ois.readObject();
		}else if(packet.getHeader().equals(CalendarEvent.class.getName())){
			result = (ArrayList<CalendarEvent>) ois.readObject();
		}else if(packet.getHeader().equals(BusSchedule.class.getName())){
			result = (ArrayList<String>) ois.readObject();
		}
		oos.close();
		os.close();
		socket.close();
		return result;
	}
}
